package cn.sx.service;

/*
 *@program:sx_emall_ssm
 *@author: sx
 *@desc: 购物车service
 *@Time: 2020/9/20  19:27
 */

import cn.sx.dao.CartsDao;
import cn.sx.entity.Carts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CartService {
    @Autowired
    private CartsDao cartsDao;
    @Autowired
    private GoodsService goodsService;
    /*获取购物车列表*/
    public int getCount(int userId) {
        return cartsDao.selectSumAmountByUserId(userId);
    }
    /*获取购物车列表*/
    public List<Carts> getList(int userId){
        return pack(cartsDao.selectListByUseId(userId));
    }

    /*添加购物车*/
    public boolean save(int goodId, int userId) {
        Carts carts =cartsDao.selectByUserIdAndGoodId(userId,goodId);
        if (Objects.nonNull(carts)){
            return cartsDao.updateAmount(carts.getId(),1);
        }
        carts = new Carts();
        carts.setGoodId(goodId);
        carts.setUserId(userId);
        carts.setAmount(1);//默认数量1
        return cartsDao.insert(carts);
    }

    /*购物车总金额*/
    public int getTotal(int useerId) {
        int total=0;
        List<Carts>cartsList=this.getList(useerId);
        if (Objects.nonNull(cartsList) && !cartsList.isEmpty()){
            for (Carts carts : cartsList){
                total += carts.getGood().getPrice() * carts.getAmount();
            }
        }
        return total;
    }
    /*封装商品*/
    private List<Carts> pack(List<Carts> list) {
        for (Carts carts:list) {
            carts=pack(carts);
        }
        return list;
    }

    /*封装商品 */
    private Carts pack(Carts carts){
        if (Objects.nonNull(carts)){
            carts.setGood(goodsService.get(carts.getGoodId()));//类目信息
            carts.setTotal(carts.getAmount() * carts.getGood().getPrice());
        }
        return carts;
    }

    public boolean cartDelete(int id) {
        return cartsDao.delete(id);
    }

    public boolean add(int id) {
        return cartsDao.updateAmount(id,1);
    }

    public boolean less(int id) {
        Carts carts = cartsDao.select(id);
        if(carts.getAmount()<=1){
            return cartDelete(id);
        }
        return cartsDao.updateAmount(id,-1);
    }

    /*清空购物车*/
    public boolean clean(Integer userId) {
        return cartsDao.deleteByUserId(userId);
    }
}
